package zct.proj;


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import zct.proj.customView.StationDisplay;
import zct.proj.util.CommUtil;
import zct.proj.util.Const;
import zct.proj.util.CustomAdapter;
import zct.proj.util.CustomAddedListAdapter;
import zct.proj.util.ListItemInterface;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MapActivity extends Activity implements ListItemInterface {

	private StationDisplay stationView;
	private AudioManager audioManager=null; //音频
//	private List<HashMap<String, Object>> mData;
	
	public void setLockPatternEnabled(boolean enabled) {
    	getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setBoolean(android.provider.Settings.System.LOCK_PATTERN_ENABLED,
                enabled);
    }
    private void setBoolean(String systemSettingKey, boolean enabled) {
        android.provider.Settings.System.putInt(getContentResolver(),
                systemSettingKey, enabled ? 1 : 0);
    }
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		if (stationView != null) {
//			Log.v("mapact", "stationView already existed, skip onCreate event---------");
//			return;
//		} else {
//			Log.v("mapact", "create new instance of stationView---------");
//		}
		audioManager=(AudioManager)getSystemService(Service.AUDIO_SERVICE);
		int step = 0;
//		try {
		Intent intent = getIntent();
		String sName = intent.getStringExtra(Const.KEY_STATION_NAME);
		setContentView(R.layout.station);
		FrameLayout bk = (FrameLayout) this.findViewById(R.id.mapBg);
		stationView = new StationDisplay(this, sName);
		step = 1;
		if (savedInstanceState != null) {
			step = 2;
	    	String[] keys = savedInstanceState.getStringArray("AlarmKey");
	    	if (keys != null) {
	    		int[] values = savedInstanceState.getIntArray("AlarmIndex");
		    	HashMap<String, Integer> m = new HashMap<String, Integer>();
		    	step = 3;
		    	for (int i = 0; i < keys.length; i++) {
		    		m.put(keys[i], values[i]);
		    	}
		    	step = 4;
		    	stationView.swStatusMap = m;
		    	stationView.addedSw = savedInstanceState.getStringArrayList("AddedSw");
		    	step = 5;
		    	keys = savedInstanceState.getStringArray("ListKey");
		    	String[] vals = savedInstanceState.getStringArray("ListValue");
		    	// 定位报警列表
		    	HashMap<String, String> mp = new HashMap<String, String>();
		    	step = 6;
		    	for (int i = 0; i < keys.length; i++) {
		    		mp.put(keys[i], vals[i]);
		    	}
		    	step = 7;
		    	stationView.warningSwCtlList = mp;
		    	step = 8;
		    	reloadAddedListDataSource();
	    	}
	    	
		}
		step = 9;
		bk.addView(stationView);
		step = 10;
        LinearLayout listLayout = (LinearLayout) this.findViewById(R.id.warnListLayout);
        listLayout.setBackgroundColor(Color.BLACK);
		setLockPatternEnabled(true);
		step = 11;
		Button b = (Button) this.findViewById(R.id.closebutton);
		b.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				stationView.setListLayout(false);
			}
		});
		step = 12;
//		} catch(Exception ex) {
//			AlertDialog.Builder builder = new AlertDialog.Builder(this);  
//			builder.setMessage("启动程序时发生错误。\rstep:" + step + "\rmsg:"+ex.getMessage());  
//			  
//			builder.setTitle("提示");  
//			builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() {
//				@Override
//				public void onClick(android.content.DialogInterface dialog, int which) {
//				    dialog.dismiss();
//				}
//			});
//			  
//			builder.create().show();
//		}
		
        resumeBrightness();
	}
	
	private void resumeBrightness() {
        // 设置屏幕亮度
		float bri = CommUtil.getBrightness();
		if (bri > 0) {
			WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes();
			layoutParams.screenBrightness = bri;
			// 重新设置窗口的属性
	        this.getWindow().setAttributes(layoutParams);
		}
	}

	
	public boolean onKeyDown(int keyCode, KeyEvent event) { 
		// 如果是返回键,直接返回到桌面 
		if(keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME){ 
			confirmExit(); 
		} 

		return super.onKeyDown(keyCode, event); 
	}
	
	protected void confirmExit() {  
		AlertDialog.Builder builder = new AlertDialog.Builder(this);  
		builder.setMessage("是否要退出？");  
		  
		builder.setTitle("提示");  
		builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() {
			@Override
			public void onClick(android.content.DialogInterface dialog, int which) {
			    dialog.dismiss();
			    Intent intent = new Intent(MapActivity.this, ZctActivity.class);
			    setResult(RESULT_OK, intent);
			    stationView.endAllTask();
			    stationView = null;
			    MapActivity.this.finish();  
			}
		});
		  
		builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {  
			@Override  
			public void onClick(android.content.DialogInterface dialog, int which) {  
				dialog.dismiss();  
			}  
		});  
		  
		builder.create().show();
	 }
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		MenuItem item = menu.findItem(Menu.FIRST + 3);
		if (stationView.getScreenLock()) {
			item.setTitle("解锁");
			item.setIcon(R.drawable.menu_unlock);
		} else {
			item.setTitle("锁屏");
			item.setIcon(R.drawable.menu_lock);
		}
		return true;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//menu.add(Menu.NONE, Menu.FIRST + 1, 2, "退出").setIcon(android.R.drawable.ic_menu_save);
		menu.add(Menu.NONE, Menu.FIRST + 2, 1, "返回").setIcon(R.drawable.menu_back);
		menu.add(Menu.NONE, Menu.FIRST + 3, 3, "锁屏").setIcon(R.drawable.menu_lock);
		menu.add(Menu.NONE, Menu.FIRST + 4, 4, "设置").setIcon(R.drawable.menu_gear);

		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case Menu.FIRST + 1:
			confirmExit();
			break;
		case Menu.FIRST + 2:
			stationView.endAllTask();
			stationView = null;
			finish();
			break;
		case Menu.FIRST + 3:
			boolean lock = !stationView.getScreenLock();
			stationView.setScreenLock(lock);
			break;
		case Menu.FIRST + 4:
			showAdjustDialog();
//            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, 
//                    AudioManager.ADJUST_SAME, 
//                    AudioManager.FLAG_SHOW_UI);    //调高声音
			break;
		case Menu.FIRST + 5:
            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, 
                    AudioManager.ADJUST_LOWER, 
                    AudioManager.FLAG_SHOW_UI);//调低声音
			break;
		}
		return true;
	}

	private void showAdjustDialog() {
		final AlertDialog dlg = new AlertDialog.Builder(this).create();
		dlg.show();
		Window window = dlg.getWindow();
		        // *** 主要就是在这里实现这种效果的.
		        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
		window.setContentView(R.layout.setting);
		        // 为确认按钮添加事件,执行退出应用操作
		Button ok = (Button) window.findViewById(R.id.btnclose);
		ok.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				dlg.dismiss();
			}
		});
		
		SeekBar sndBar = (SeekBar) window.findViewById(R.id.volumeBar);
		// 获取系统最大音量
		int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);  
		// 拖动条最高值与系统最大声匹配
		sndBar.setMax(maxVolume);  
		// 获取当前值
        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        // 设置当前音量
        sndBar.setProgress(currentVolume);
        sndBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        	@Override
            public void onProgressChanged(SeekBar arg0,int progress,boolean fromUser)  
            {  
            	audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);    
//                currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);  //获取当前值  
//                sndBar.setProgress(currentVolume);    
            }

			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}
        });
        
        SeekBar briBar = (SeekBar) window.findViewById(R.id.brightBar);
        briBar.setMax(50);
        int bright = (int)(CommUtil.getBrightness() * 100);
        if (bright == 0) {
			try {
				bright = android.provider.Settings.System.getInt(
					    getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS);
				bright = (int) ((float) bright / 255 * 100);
			} catch (SettingNotFoundException e) {
				e.printStackTrace();
			}
        }
		briBar.setProgress(bright - 50);
        briBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
//				WindowManager.LayoutParams layoutParams = MapActivity.this.getWindow().getAttributes();
		        // 设置屏幕亮度
				float bri = (float) (progress + 50) / 100;
				CommUtil.setBrightness(bri);
				resumeBrightness();
//		        layoutParams.screenBrightness = bri;
//		        // 重新设置窗口的属性
//		        MapActivity.this.getWindow().setAttributes(layoutParams);
//					int bright = android.provider.Settings.System.getInt(
//						    getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS, 255);
					//briBar.setProgress(bright);
			}
		});
	}
	
	CustomAdapter adapter;
	CustomAddedListAdapter addAdapter;
	
	@Override
	public void reloadDataSource() {
		
		if (adapter == null) {
			adapter = new CustomAdapter(this, stationView.currentSw);
			adapter.setAddedList(stationView.addedSw);
			ListView listView = (ListView) this.findViewById(R.id.listView);
			listView.setAdapter(adapter);
		} else {
			adapter.setData(stationView.currentSw);
			adapter.notifyDataSetChanged();
		}
		
        
	}
	
	private void reloadAddedListDataSource() {
		if (addAdapter == null) {
			addAdapter = new CustomAddedListAdapter(this, stationView.addedSw);
			ListView listView = (ListView) this.findViewById(R.id.addedListView);
	        listView.setAdapter(addAdapter);
		} else {
//			addAdapter.setData(stationView.currentSw);
			addAdapter.notifyDataSetChanged();
		}
	}
	
	@Override
	public void itemButtonClicked(View v) {
		Button b = (Button) v;
		String swName = b.getTag().toString();
		if (b.getText().equals("添加")) {
			stationView.addSelectedEquipToList(swName);
		} else {
			stationView.removeItemFromList(swName);
		}
		reloadDataSource();
		reloadAddedListDataSource();		
		//Log.i("MapAct", v.getTag().toString());
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if (stationView != null) {
			stationView.stopDrawing();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (stationView != null) {
			stationView.startDrawing();
		}
	}
	
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save away the original text, so we still have it if the activity
        // needs to be killed while paused.
//      savedInstanceState.putInt("IntTest", mCount);
//      savedInstanceState.putString("StrTest", "savedInstanceState test");
//    	savedInstanceState.put
    	if (stationView != null && stationView.swStatusMap.size() > 0) {
    		Iterator<Entry<String, Integer>> it = stationView.swStatusMap.entrySet().iterator();
    		String[] keys = new String[stationView.swStatusMap.size()];
    		int[] values = new int[keys.length];
    		int idx = 0;
    		while (it.hasNext()) {
				Entry<String, Integer> entry = it.next();
				keys[idx] = entry.getKey();
				values[idx] = entry.getValue();
				idx++;
    		}
    		savedInstanceState.putStringArray("AlarmKey", keys);
    		savedInstanceState.putIntArray("AlarmIndex", values);
    		savedInstanceState.putStringArrayList("AddedSw", stationView.addedSw);
    		
    		Iterator<Entry<String, String>> itt = stationView.warningSwCtlList.entrySet().iterator();
    		keys = new String[stationView.warningSwCtlList.size()];
    		String[] vals = new String[keys.length];
    		idx = 0;
    		while (it.hasNext()) {
				Entry<String, String> entry = itt.next();
				keys[idx] = entry.getKey();
				vals[idx] = entry.getValue();
				idx++;
    		}
    		savedInstanceState.putStringArray("ListKey", keys);
    		savedInstanceState.putStringArray("ListValue", vals);
    		
//    		Log.v("MapAct", "onSaveInstanceState save " + stationView.addedSw.size() + " sw.");
    	}
    	super.onSaveInstanceState(savedInstanceState);
//      Log.e(TAG, "onSaveInstanceState");
    }  
//    @Override
//	public void onRestoreInstanceState(Bundle savedInstanceState) {
//    	super.onRestoreInstanceState(savedInstanceState);
//    	String[] keys = savedInstanceState.getStringArray("AlarmKey");
//    	int[] values = savedInstanceState.getIntArray("AlarmIndex");
//    	HashMap<String, Integer> m = new HashMap<String, Integer>();
//    	for (int i = 0; i < keys.length; i++) {
//    		m.put(keys[i], values[i]);
//    	}
//    	stationView.swStatusMap = m;
////      int mCount = savedInstanceState.getInt("IntTest");
////      String StrTest = savedInstanceState.getString("StrTest");
////      Log.e(TAG, "onRestoreInstanceState+IntTest="+mCount+"+StrTest="+StrTest);
//    }
  
	public void onDestroy()
	{
		super.onDestroy();
		if (stationView != null) {
			stationView.endAllTask();
		}
	}
}
